#coding=utf-8
#Created on 2011-06-14
#@author: butter
import copy
import base64
import datetime
import ujson as json

from django.conf import settings

from django_jinja import library

from common.utils import tool

register = library.Library()

@register.global_function
def static(path, version='auto'):
    '''
    funciton: 获取静态资源（如js，css，image，font）等的url地址
    path - 静态资源文件相对路径
    version - 人工版本控制的版本号，如果version为空，则采用 settings.PROJECT_VERSION
    '''
    
    if version == 'auto':
        return '%s%s?v=%s' % (settings.STATIC_URL, path, settings.PROJECT_VERSION)
    elif version == 'ignore':
        return '%s%s' % (settings.STATIC_URL, path)
    else:
        return '%s%s?v=%s' % (settings.STATIC_URL, path, version)   
    
@register.global_function
def currency_format(val):
    
    return '%.2f' % val

@register.global_function
def rmb_yuan(val):
    '''
    将整形分转换为浮点数元
    '''
    return '%.2f' % (val / 100.0)

@register.global_function
def wrap_word(string, length=15, ext='...'):
    if len(string) > length:
        return '%s%s' % (string[0:length], ext)
    return string

@register.global_function
def time_beauty(val):
    if isinstance(val, str):
        val = datetime.datetime.strptime(val, '%Y-%m-%d %H:%M:%S')
    now_time = datetime.datetime.now()
    delta_time = now_time - val
    delta_date = now_time.date() - val.date()
    time_str = u''

    if delta_time.seconds < 60 and delta_time.days < 1:
        time_str = '刚刚'
    elif delta_time.seconds < 60 * 60 and delta_time.days < 1:
        time_str = '%i分钟前' % (delta_time.seconds / 60)
    elif delta_date.days < 1:
        time_str = val.strftime('今天 %H:%M')
    elif delta_date.days < 2:
        time_str = val.strftime('昨天 %H:%M')
    elif now_time.year == val.year:
        time_str = val.strftime('%m月%d日')
    else:
        time_str = val.strftime('%Y年%m月%d日')

    return time_str.decode('utf8')

@register.global_function
def date_beauty(val):
    return val.strftime('%Y年%m月%d日').decode('utf-8')

@register.global_function
def media(val):
    '''
    文件上传地址
    '''
    return '%s%s' % (settings.MEDIA_URL, val)


@register.global_function
def now(format):
    '''
    现在时间
    '''
    return datetime.datetime.now().strftime(format)


@register.global_function
def highlight(val, keyword):
    '''
    高亮显示
    '''
    highlight_html = val.replace(keyword, '<span class="text-orange">%s</span>' % keyword)
    return highlight_html


@register.global_function
def short_url(name, *args):
    url = '/%s' % name
    for arg in args:
        url += '-%s' % arg
    return url + '/'


@register.global_function
def thumbnail_square(img):
    """正方形缩略图"""
    file_type = img.split('.')[-1]
    return '%s.%s.%s' % (img, 'square', file_type)

@register.global_function
def thumbnail_big(img):
    """大 缩略图"""
    file_type = img.split('.')[-1]
    return '%s.%s.%s' % (img, 'big', file_type)

@register.global_function
def mobile_display(mobile, full=False):
    """手机展示处理"""
    
    try:
        mobile = str(mobile)
        if mobile and (not full):
            mobile = mobile.replace(mobile[5:9], '****')
    except:
        pass
    return mobile

@register.global_function
def make_timestamp(t):
    """手机展示处理"""
    
    return tool.make_timestamp(t)

@register.global_function
def json_dumps(pyobj):
    '''
    将python对象dumps成json字符串
    '''
    return json.dumps(pyobj)


@register.global_function
def base64_encode(s):
    '''
    将字符串进行base64编码
    '''
    return base64.b64encode(s)

